import { useEffect, useRef, useState } from "react";

interface TimerIntervalProps {
    interval: number;
    onEnd: () => void;
    onIntervalChange: (interval: number) => void;
}
export const TimerInterval = ({ interval = 60, onEnd }: TimerIntervalProps) => {
    const [duration, setDuration] = useState(interval);
    const timerRef = useRef<NodeJS.Timeout | null>(null);


    const autoUpdateTime = ()=>{
        setDuration((pre : number)=>{
            if(pre < 1){
                onEnd?.();
                clearInterval(timerRef.current as NodeJS.Timeout);
                return pre;
            }
            return pre- 1;
        })
    }
    useEffect(()=>{
        timerRef.current = setInterval(()=>{
            autoUpdateTime();
        },1000)
        return ()=>{
            clearInterval(timerRef.current as NodeJS.Timeout);
        }
    },[])
    return <div>
        {duration}s
    </div>;
};